<script setup lang="ts">
import {ref, computed, reactive, watch} from 'vue';
import type {FormItem} from '@/components/AForm/form.type.d';
import {AForm} from '@/components/index';
import {useForm, useDict} from '@/hooks/index';
import {formatOption} from '@/utils/formatOption';
import {delay} from '@/utils/delay';
import {userDetailGET, userPOST, userPUT} from '@/services/system/user.service';

const props = defineProps<{
  visible: boolean;
  id?: string | undefined;
  deptTreeData: any[];
}>();
const emit = defineEmits<{
  'update:visible': [value: boolean];
  request: [];
}>();

const formData = reactive({
  nickName: '', //用户昵称
  deptId: '', //归属部门
  phonenumber: '', //手机号码
  email: '', //邮箱
  userName: '', //用户名称
  password: '', //用户密码
  sex: '', //用户性别
  status: '', //状态
  postIds: undefined, //岗位 多选
  roleIds: undefined, //角色 多选
  remark: '', //备注
});
const rules = reactive({
  nickName: [{required: true, message: '请输入用户昵称', maxlength: 30}],
  deptId: [{required: true, message: '请选择归属部门'}],
  phonenumber: [{required: true, message: '请输入手机号码', maxlength: 11}],
  email: [{required: true, message: '请输入邮箱', maxlength: 20}],
  userName: [{required: true, message: '请输入用户名称', maxlength: 20}],
  password: [{required: true, message: '请输入用户密码', maxlength: 20}],
  sex: [{required: true, message: '请选择性别'}],
  status: [{required: true, message: '请选择状态'}],
  postIds: [{required: true, message: '请选择岗位'}],
  roleIds: [{required: true, message: '请选择角色'}],
});
const commonFormItem = [
  {label: '用户昵称', itemKey: 'nickName', itemType: 'input', col: 12},
  {label: '归属部门', itemKey: 'deptId', itemType: 'tree-select', options: [], col: 12},
  {label: '手机号码', itemKey: 'phonenumber', itemType: 'input', col: 12},
  {label: '邮箱', itemKey: 'email', itemType: 'input', col: 12},
  {label: '用户名称', itemKey: 'userName', itemType: 'input', col: 12},
  {label: '用户密码', itemKey: 'password', itemType: 'input', col: 12},
  {label: '用户性别', itemKey: 'sex', itemType: 'select', col: 12},
  {label: '状态', itemKey: 'status', itemType: 'select', col: 12},
  {label: '岗位', itemKey: 'postIds', itemType: 'select', mode: 'multiple', col: 12},
  {label: '角色', itemKey: 'roleIds', itemType: 'select', mode: 'multiple', col: 12},
  {label: '备注', itemKey: 'remark', itemType: 'input', col: 24},
];
const formItem = ref<FormItem[]>(commonFormItem);
const confirmLoading = ref<boolean>(false);
const visible = computed({
  get: () => props.visible,
  set: (value) => {
    if (!value) {
      confirmLoading.value = false;
      handleReset();
    }
    emit('update:visible', value);
  },
});
const title = computed(() => {
  if (props.id) return '修改用户';
  return '新增用户';
});
const {validateInfos, handleSubmit, handleReset} = useForm({
  formData,
  rules,
  submit: async () => {
    confirmLoading.value = true;
    let result;
    if (props.id) {
      result = await userPUT({...formData, userId: props.id});
    } else {
      result = await userPOST(formData);
    }
    await delay(500);
    if (result?.code === 200) {
      emit('request');
      emit('update:visible', false);
    }
    confirmLoading.value = false;
    // console.log('result', result);
    // console.log('传参=》', formData);
  },
});

const getUser = async () => {
  if (props.id) {
    rules.userName[0].required = false;
    rules.password[0].required = false;
    formItem.value = commonFormItem.filter((item) => item.itemKey !== 'userName' && item.itemKey !== 'password');
  } else {
    formItem.value = commonFormItem;
  }
  const {sys_normal_disable, sys_user_sex} = useDict('sys_normal_disable', 'sys_user_sex');
  const result = await userDetailGET(props?.id);
  if (result?.code === 200) {
    formItem.value = formItem.value?.map((item) => {
      if (item.itemKey === 'deptId') {
        const recursionTree = (data: any[]) => {
          return data.map((item: any) => {
            item.value = item.id;
            if (item.children) recursionTree(item.children);
            return item;
          });
        };
        const tempData = recursionTree(props.deptTreeData);
        item.options = tempData || [];
      }
      if (item.itemKey === 'postIds') {
        item.options = formatOption(result.posts, {label: 'postName', value: 'postId'});
      }
      if (item.itemKey === 'roleIds') {
        item.options = formatOption(result.roles, {label: 'roleName', value: 'roleId'});
      }
      if (item.itemKey === 'sex') {
        item.options = formatOption(sys_user_sex.value, {label: 'label', value: 'value'});
      }
      if (item.itemKey === 'status') {
        item.options = formatOption(sys_normal_disable.value, {label: 'label', value: 'value'});
      }
      return item;
    });
    // console.log('详情=>', result);
    if (result?.data) {
      formData.nickName = result.data.userName;
      formData.deptId = result.data.deptId;
      formData.phonenumber = result.data.phonenumber;
      formData.email = result.data.email;
      formData.userName = result.data.userName;
      formData.password = result.data.password;
      formData.sex = result.data.sex;
      formData.status = result.data.status;
      formData.postIds = result.postIds;
      formData.roleIds = result.roleIds;
      formData.remark = result.data.remark;
    }
  }
};
watch(
  () => props.visible,
  (nextState) => {
    if (nextState) {
      getUser();
    }
  },
);
</script>

<template>
  <div class="container">
    <a-modal v-model:open="visible" :title="title" width="700px" @ok="handleSubmit" :confirmLoading="confirmLoading">
      <AForm :formData="formData" :formItem="formItem" :validateInfos="validateInfos" :query="false"> </AForm>
    </a-modal>
  </div>
</template>

<style lang="less" scoped></style>
